package com.leo.foodmaster.commons.config.security;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.leo.foodmaster.commons.constants.HttpStatus;
import com.leo.foodmaster.commons.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * 自定义鉴权失败处理类 返回未授权
 * </p>
 *
 * @author ：Leo
 * @since ：2021-06-18 11:39
 */
@Slf4j
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    /**
     * 返回前端响应结果
     * @param response 响应
     * @param result 结果
     */
    private void writeResult(HttpServletResponse response, String result) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        PrintWriter writer = response.getWriter();
        writer.append(result);
    }


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        log.error(StrUtil.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI()));

        // 密码错误异常处理
        if (e instanceof BadCredentialsException) {
            String result = JSONUtil.toJsonPrettyStr(Result.fail(HttpStatus.FORBIDDEN, e.getMessage()));
            writeResult(response, result);
        }
    }
}
